import tkinter as tk
from tkinter import ttk, messagebox
import json
import sys
import os
import json
import sys
import tkinter as tk
from tkinter import messagebox

def load_config(config_path):
    """加载配置文件"""
    if not os.path.exists(config_path):
        print(f"Error: {config_path} not found.")
        return None
    
    try:
        with open(config_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except json.JSONDecodeError as e:
        print(f"Error: Invalid JSON format in {config_path}: {e}")
        return None
    except PermissionError:
        print(f"Error: Permission denied when accessing {config_path}")
        return None
    except Exception as e:
        print(f"Error loading config file: {e}")
        return None

class LoginWindow:
    def __init__(self, master, on_login_success):
        self.master = master
        self.master.title("用户登录")
        self.master.geometry("300x200")
        self.on_login_success = on_login_success
        
        # 创建登录界面
        self.create_login_window()
        
    def create_login_window(self):
        # 主框架
        main_frame = ttk.Frame(self.master, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 标题
        ttk.Label(main_frame, text="用户登录", font=("Arial", 16, "bold")).grid(row=0, column=0, columnspan=2, pady=10)
        
        # 用户名
        ttk.Label(main_frame, text="用户名:").grid(row=1, column=0, sticky=tk.W, pady=5)
        self.username_var = tk.StringVar()
        ttk.Entry(main_frame, textvariable=self.username_var).grid(row=1, column=1, padx=5, pady=5)
        
        # 密码
        ttk.Label(main_frame, text="密码:").grid(row=2, column=0, sticky=tk.W, pady=5)
        self.password_var = tk.StringVar()
        ttk.Entry(main_frame, textvariable=self.password_var, show="*").grid(row=2, column=1, padx=5, pady=5)
        
        # 登录按钮
        ttk.Button(main_frame, text="登录", command=self.validate_login).grid(row=3, column=0, columnspan=2, pady=10)
        
    def validate_login(self):
        username = self.username_var.get()
        password = self.password_var.get()
        
        # 获取当前脚本的目录
        current_dir = os.path.dirname(os.path.abspath(__file__))
        config_path = os.path.join(current_dir, 'config.json')
        
        # 从配置文件加载用户信息
        config = load_config(config_path)
        if config is None:
            messagebox.showerror("错误", "无法加载配置文件")
            return
        
        users = config.get('users', [])
        
        for user in users:
            if user.get('username') == username and user.get('password') == password:
                self.master.destroy()
                self.on_login_success()
                return
                
        messagebox.showerror("登录失败", "用户名或密码错误")

def show_login_window(on_login_success):
    root = tk.Tk()
    app = LoginWindow(root, on_login_success)
    root.mainloop()